package com.zigong.app.ui.activities;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.base.BaseCanPlayActivity;
import com.zigong.app.application.Constances;
import com.zigong.app.beans.ADynamicsItem;
import com.zigong.app.beans.AFileItem;
import com.zigong.app.beans.AHomePageItem;
import com.zigong.app.beans.FProgramme;
import com.zigong.app.beans.FUsers;
import com.zigong.app.beans.NewsItem;
import com.zigong.app.beans.SingleResult;
import com.zigong.app.beans.Titles;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.http.ParamsEditor;
import com.zigong.app.ui.adapter.AnchorHomePageAdapter;
import com.zigong.app.ui.adapter.holder.AnchorHomeDynamicsHolder;
import com.zigong.app.ui.util.IListShowData;
import com.zigong.app.ui.utils.GPlayerBottomControllerImp;
import com.zigong.app.ui.utils.GSFPlayerScreenControllImp;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.ui.utils.TitleUtils;
import com.zigong.app.ui.widget.BasePlayerView;
import com.zigong.app.utils.UserManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 主播个人主页（主播详情）
 */
public class AnchorHomePageActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.IScrollView {
    @BindView(R.id.anchor_home_refreshLayout)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.anchor_home_page_ll)
    protected LinearLayout top_ll;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.anchor_home_page_list)
    protected RecyclerView recyclerView;
    private Handler handler;
    private String titleStr;
    private AnchorHomePageAdapter adapter;
    private LinearLayoutManager manager;
    private String homePageUrl;
    private GPlayerBottomControllerImp bottomController;
    private GSFPlayerScreenControllImp screenControllImp;
    private String contentVideoUrl;
    private ADynamicsItem dynamicsTemp;
    private int tempPos;
    private int height;

    private BasePlayerView videoPlayers;

    private int index = 0;
    private final static int pageSize = 10;
    private int relateIndex = 0;
    private final static int relatePageSize = 10;
    private final static int totalCount = 30;
    private final static int ANCHOR_SCTV_TYPE = 0;
    private final static int ANCHOR_SC_TYPE = 1;
    private List<ADynamicsItem> dyDatas;
    List<IListShowData> list = new ArrayList<>();
    private boolean isMoreDynamics = false;
    private String anchorId;
    private ArrayList<IListShowData> relateNews = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        handler = new Handler();
        isVideoTop = false;
        homePageUrl = getIntent().getStringExtra(EX_URL);
        titleStr = getIntent().getStringExtra(EX_TITLE);
        anchorId = getIntent().getStringExtra(EX_ID);
        initViews();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_anchor_home_page);
        ButterKnife.bind(this);
    }

    @NonNull
    @Override
    protected BasePlayerView createdPlayerView() {
        if (videoPlayers == null) {
            videoPlayers = new BasePlayerView(this);
        }
        return videoPlayers;
    }

    @Override
    protected StandardGSYVideoPlayer getVideoPlayer() {
        return videoPlayers;
    }

    private void initViews() {
        final int pa = getResources().getDimensionPixelOffset(R.dimen.divider_shadow_margin_bottom);
        top_ll.postDelayed(new Runnable() {
            @Override
            public void run() {
                height = top_ll.getHeight() + pa;
            }
        }, 300);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(manager);
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();

    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            index++;
            getTimeLineList();
//            currentPage = currentPage + 1;
//            if (currentPage < pageAll) {
////                getAHomePageList(currentPage);
//            }
        }
    }


    @Override
    public void onRefresh() {
        index = 0;
        getAHomePageList(index);
    }

    @Override
    protected void onDestroy() {
        if (floatVideoUtils != null) {
            recyclerView.removeOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
        }
        super.onDestroy();
    }

    /**
     * 获取主播主数据
     *
     * @param calledPage
     */
    private void getAHomePageList(int calledPage) {
        if (TextUtils.isEmpty(homePageUrl)) {
            toast("数据错误");
            return;
        }
        NetUtils.getNetAdapter().getAHomePageList(getOwnerName(), homePageUrl, calledPage
                , new AbsNetCallBack<AHomePageItem>(AHomePageItem.class, calledPage) {
                    @Override
                    public void onSuc(AHomePageItem aHomePageItem) {
                        // JLog.e("====data==" + aHomePageItem);
                        if (aHomePageItem != null) {
//                            pageAll = aHomePageItem.getPageAll();
//                            currentPage = aHomePageItem.getPageIndex();
                            setPageData(aHomePageItem);
                            getRelateNews();

                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                    }
                });
    }

    /**
     * 请求主播关联的新闻数据
     */
    private void getRelateNews() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("anchorId", anchorId);
        param.put("count", relatePageSize);
        param.put("index", relateIndex);
        param.put("siteNumber", Constances.SITE_ID);
        NetUtils.getNetAdapter().getAnchorRelateNewsList(getOwnerName(), param, new AbsListNetCallback<NewsItem>(NewsItem.class) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                JLog.e("getRelateNews:" + newsItems.toString());
                if (relateIndex == 0) {
                    relateNews = new ArrayList<>();
                    if (ListUtils.isListValued(newsItems)) {
                        Titles titles = new Titles();
                        titles.setTitle(getString(R.string.anchor_news));
                        titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
                        relateNews.add(titles);
                    }
                    relateNews.addAll(newsItems);
                    list.addAll(relateNews);
                } else {
                    relateNews.addAll(newsItems);
                }
                getTimeLineList();
            }

            @Override
            public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                ArrayList<NewsItem> temp = new ArrayList<>();
                if (newsItems.size() > 5) {
                    for (int i = 0; i < 5; i++) {
                        if (i == 4) {
                            newsItems.get(i).setLastItem(true);
                        } else {
                            newsItems.get(i).setLastItem(false);
                        }
                        temp.add(newsItems.get(i));
                    }
                } else {
                    temp.addAll(newsItems);
                }
                for (NewsItem item : temp) {
                    item.setViewType(AnchorHomePageAdapter.VIEWTYPE_HOME_NEWS);
                }
                return super.doInBackground(temp);
            }
        });

    }

    /**
     * 主播相关发布动态数据请求
     */
    private void getTimeLineList() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("anchorId", anchorId);
        param.put("capacity", pageSize);
        param.put("index", index);
        param.put("requestType", ANCHOR_SCTV_TYPE);
        param.put("siteNumber", Constances.SITE_ID);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }
        NetUtils.getNetAdapter().getTimelineList(getOwnerName(), param, new AbsListNetCallback<ADynamicsItem>(ADynamicsItem.class) {
            @Override
            public void onSuc(List<ADynamicsItem> anchortimelines) {

                if (dyDatas == null) {
                    dyDatas = new ArrayList<>();
                }
                if (index == 0) {//第一次加載或者下拉刷新后 index重置為0；
                    dyDatas.clear();
                    if (ListUtils.isListValued(anchortimelines)) {
                        ADynamicsItem firstItem = anchortimelines.get(0);
                        firstItem.setDynamics(true);
                        firstItem.setSticky(true);
                        if (anchortimelines.size() >= pageSize) {//如果獲取的數據大於10條 則加載更多
//                            ADynamicsItem lastItem = anchortimelines.get(anchortimelines.size() - 1);
//                            lastItem.setMore(true);
                            isMoreDynamics = true;
                        } else {
                            isMoreDynamics = false;
                        }
                        dyDatas.addAll(0, anchortimelines);
                        list.addAll(dyDatas);
                    }

                } else {
                    if (list != null && list.containsAll(dyDatas)) {
                        list.removeAll(dyDatas);
                    }
                    dyDatas.get(dyDatas.size() - 1).setMore(false);
                    if (anchortimelines.size() >= pageSize) {//如果獲取的數據大於10條 則加載更多
//                        ADynamicsItem lastItem = anchortimelines.get(anchortimelines.size() - 1);
//                        lastItem.setMore(true);
                        isMoreDynamics = true;
                    } else {
                        isMoreDynamics = false;
                    }
                    dyDatas.addAll(anchortimelines);
//                    if (dyDatas.size() >= totalCount) {//加载30条后还有更多则跳转
//                        dyDatas.get(dyDatas.size() - 1).setJump(true);
//                    }
                    list.addAll(dyDatas);
                }

                if (adapter == null) {
                    adapter = new AnchorHomePageAdapter(AnchorHomePageActivity.this, list);
                    adapter.setInAnchorDetail(true);
                    adapter.setPlayClick(playOnItemClick);
                    ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                    pairs.add(new Pair<>("页面", "主播档案页"));
                    pairs.add(new Pair<>("行为类型", "点击"));
                    adapter.setPairs(pairs);
                    adapter.setActivity(AnchorHomePageActivity.this);
                    recyclerView.setAdapter(adapter);
                } else {
                    adapter.setData(list);
                }

            }

            @Override
            public List<ADynamicsItem> doInBackground(List<ADynamicsItem> aDynamicsItems) {
                if (aDynamicsItems != null) {
                    for (ADynamicsItem item : aDynamicsItems) {
                        item.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
                    }
                }

                return super.doInBackground(aDynamicsItems);
            }

            @Override
            public void onEnd() {
                onNetFinish();
                super.onEnd();
            }
        });


    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(isMoreDynamics);
    }

    /**
     * 初始化主播个人主数据UI
     *
     * @param data
     */
    private void setPageData(AHomePageItem data) {
        if (index == 0) {
            list.clear();
        }
        List<FProgramme> programList = data.getProgramList();
//        List<ADynamicsItem> dynamics = data.getAnchorDynamic();
        AFileItem anchorInfo = data.getAnchorInfo();
        if (anchorInfo != null) {
            anchorInfo.setViewType(AnchorHomePageAdapter.VIEWTYPE_HOME_FILE);
            list.add(anchorInfo);
        }
        Titles titles = null;
        if (ListUtils.isListValued(programList)) {
            titles = new Titles();
            titles.setTitle(getString(R.string.anchor_column));
            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
            list.add(titles);
            for (FProgramme program : programList) {
                program.setViewType(AnchorHomePageAdapter.VIEWTYPE_COLUMN);
            }
            list.addAll(programList);
        }
//        if (ListUtils.isListValued(dynamics)) {
//            titles = new Titles();
//            titles.setTitle(getString(R.string.anchor_dynamics));
//            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
//            list.add(titles);
//            for (ADynamicsItem dynamicsItem : dynamics) {
////                dynamicsItem.setCoverImage("/sctv/1/image/public/201708/20170828112101_pex8ecr7nr.jpg");
////                dynamicsItem.setContentVideo("http://baobab.wdjcdn.com/1455969783448_5560_854x480.mp4");
//                dynamicsItem.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
//            }
//            list.addAll(dynamics);
//        }

    }


//    private void playVideo(View topImg, String url, String title, int pos) {
//        int netType = NetModeUtil.GetNetype(this);
//        JLog.e("netType=" + netType);
//        if (TextUtils.isEmpty(url)) {
//            toast(R.string.loading_invalid_data);
//            return;
//        }
//
//        if (initFloatVideoUtils(topImg, videoContainer, height)) {
//            recyclerView.addOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
//        }
//        JLog.e("netType=" + netType);
    // if (netType == 1) {   //wifi情况下直接播放
//        floatVideoUtils.setLiving(false).play(topImg, url);
    //   floatVideoUtils.play(topImg, url, title, true);
//        if (videoPlayers == null) {
//            floatVideoUtils.showPlayer(topImg, false);
//        }
//        videoPlayers.setUp(url, false, title);
//        if (pos > 0) {
//            videoPlayers.setPlayPosition(pos);
//        }
//        videoPlayers.startPlay();
//        } else {
//            showNetDialog();   //无WiFi情况下弹框提示
//        }
//    }

    OnItemInternalClick playOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.item_anchor_home_dynamics_video_play:
                    if (floatVideoUtils != null && floatVideoUtils.isShowing()) {
                        int currentPos = 0;
//                        floatVideoUtils.getPlayerView().getCurrentPosition();
                        dynamicsTemp = (ADynamicsItem) adapter.getItem(tempPos);
                        dynamicsTemp.setCurrentPos(currentPos / 1000);
                    }
                    ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
                    contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
                    playView = view;
                    toVideoPlay(contentVideoUrl, dynamics.getCurrentPos(), position);
                    tempPos = position;
                    break;
                case R.id.tv_anchor_up:
                    //点赞
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    ADynamicsItem dyUp = (ADynamicsItem) adapter.getItem(position);
//                    if (dyUp.getAttitudesStatus()) {
//                        toast("已经点过赞啦");
//                        return;
//                    }
                    doUp(dyUp, position);
                    break;
                case R.id.tv_anchor_comment:
                    //评论
                    ADynamicsItem adi = (ADynamicsItem) adapter.getItem(position);
                    Intent intent = new Intent(AnchorHomePageActivity.this, CommentDetailActivity.class);
                    intent.putExtra(EX_DATA, adi);
                    intent.putExtra(EX_COMMENT_TYPE, 3);
                    startActivity(intent);
                    break;
                case R.id.tv_anchor_news_more:
                    //主播关联新闻
                    Intent moreIntent = new Intent(AnchorHomePageActivity.this, AnchorRelateNewsActivity.class);
                    moreIntent.putExtra(EX_ID, anchorId);
                    startActivity(moreIntent);
                    break;
            }

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SkipUtil.REQUEST_CODE_PLAY_BASE) {
            if (data == null || refreshLayout.isRefreshing() || adapter == null) {
                return;
            }
            int itemPos = data.getIntExtra(SkipUtil.EX_POS_ITEM, -1);
            if (itemPos >= 0) {
                ADynamicsItem item = (ADynamicsItem) adapter.getItem(itemPos);
                if (item != null) {
                    if (resultCode == RESULT_OK) {
                        item.setCurrentPos(0);
                    } else {
                        item.setCurrentPos(data.getIntExtra(SkipUtil.EX_POS, 0));
                    }
                }
            }
        }
    }

    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
//        if (title_lay != null) {
//            title_lay.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);
//        if (title_lay != null) {
//            title_lay.setVisibility(View.VISIBLE);
//        }
//        if (floatVideoUtils != null) {
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    floatVideoUtils.refreshVideoLocation();
//                }
//            }, 200);
//        }
    }

    private void toVideoPlay(String url, int pos, int itemPos) {
        SkipUtil.skipToVideoPlay(this, url, pos, itemPos);
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(recyclerView, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(recyclerView, 1);
    }

    private AnchorHomeDynamicsHolder lastHolder = null;

    private void doUp(final ADynamicsItem aDynamicsItem, int position) {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof AnchorHomeDynamicsHolder) {
            lastHolder = (AnchorHomeDynamicsHolder) recyclerView.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.getTvUp().setDrawableEnlarge();
            }
        }
        ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
        pe.put("dynamicId", aDynamicsItem.getDynamicId());
//        pe.put("token", UserManager.getInstance().getToken());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("fType", 1);//1 主播 2报料 3新闻(短视频) 4 直播
        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {
                    SkipUtil.skipToAddUserOperate(AnchorHomePageActivity.this, getOwnerName(), 13, 2, "主播圈点赞", aDynamicsItem.getDynamicId(), Cache.getInstance().getCurrentChannelId());
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i) instanceof ADynamicsItem) {
                            ADynamicsItem item = (ADynamicsItem) list.get(i);
                            if (item.getDynamicId().equals(aDynamicsItem.getDynamicId())) {
                                item.setAttitudesCount(aDynamicsItem.getAttitudesStatus() ? aDynamicsItem.getAttitudesCount() - 1 : aDynamicsItem.getAttitudesCount() + 1);
                                item.setAttitudesStatus(!aDynamicsItem.getAttitudesStatus());
                                adapter.notifyDataSetChanged();
                                if (item.getAttitudesStatus()) {
                                    addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

}

